import React from 'react'
import { Wifi, WifiOff, Loader2, AlertCircle } from 'lucide-react'
import { useSocketStore } from '../stores/socketStore'

const ConnectionStatus: React.FC = () => {
  const { 
    connectionError, 
    reconnectAttempts,
    getConnectionStatus,
    forceReconnect 
  } = useSocketStore()

  const status = getConnectionStatus()

  // 如果连接正常且没有错误，不显示状态栏
  if (status === 'connected' && !connectionError) {
    return null
  }

  const getStatusConfig = () => {
    switch (status) {
      case 'connecting':
        return {
          icon: <Loader2 className="w-4 h-4 animate-spin" />,
          text: '正在连接服务器...',
          bgColor: 'bg-yellow-50',
          textColor: 'text-yellow-800',
          borderColor: 'border-yellow-200'
        }
      
      case 'reconnecting':
        return {
          icon: <Loader2 className="w-4 h-4 animate-spin" />,
          text: `重连中... (${reconnectAttempts}/5)`,
          bgColor: 'bg-yellow-50',
          textColor: 'text-yellow-800',
          borderColor: 'border-yellow-200'
        }
      
      case 'error':
        return {
          icon: <AlertCircle className="w-4 h-4" />,
          text: connectionError || '连接出错',
          bgColor: 'bg-red-50',
          textColor: 'text-red-800',
          borderColor: 'border-red-200'
        }
      
      case 'disconnected':
        return {
          icon: <WifiOff className="w-4 h-4" />,
          text: '服务器连接断开',
          bgColor: 'bg-gray-50',
          textColor: 'text-gray-800',
          borderColor: 'border-gray-200'
        }
      
      default:
        return {
          icon: <Wifi className="w-4 h-4" />,
          text: '已连接',
          bgColor: 'bg-green-50',
          textColor: 'text-green-800',
          borderColor: 'border-green-200'
        }
    }
  }

  const config = getStatusConfig()

  return (
    <div className={`fixed top-0 left-0 right-0 p-2 text-sm z-50 border-b ${config.bgColor} ${config.textColor} ${config.borderColor}`}>
      <div className="container mx-auto flex items-center justify-between">
        <div className="flex items-center">
          {config.icon}
          <span className="ml-2">{config.text}</span>
        </div>
        {(status === 'error' || status === 'disconnected') && (
          <button 
            onClick={forceReconnect} 
            className="px-2 py-1 border rounded text-xs hover:bg-white/20"
          >
            重连
          </button>
        )}
      </div>
    </div>
  )
}

export default ConnectionStatus 